<template>
  <div class="w-full">
    <el-scrollbar>
      <el-menu mode="horizontal" :default-active="activeMenu" @select="handleMenuSelect">
        <el-menu-item v-for="route in topMenus" :key="route.path" :index="route.path">
          <EcoIcon :icon="iconClass(route.meta)" />
          <template #title>
            <span v-if="route.meta && route.meta.title">
              {{ route.meta.title }}
            </span>
          </template>
        </el-menu-item>
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts" name="TopMenus">
import { RouteRecordRaw } from 'vue-router'
import { useAuthStore, useAppStore } from '@/stores'
const topMenus = ref<RouteRecordRaw[]>([])
const authStore = useAuthStore()
const appStore = useAppStore()
const router = useRouter()
const activeTopMenuPath = useRoute().path.match(/^\/[^\/]+/)?.[0] || '/'
appStore.activeTopMenu(activeTopMenuPath)
const activeMenu = computed(() => appStore.activeTopMenuPath)
const iconClass = (mate: any) => {
  return mate.icon as string
}
/**
 * 菜单选择事件
 */
const handleMenuSelect = (routePath: string) => {
  appStore.activeTopMenu(routePath)
  authStore.setAuthLeftMenus(routePath)
  // 获取左侧菜单集合，默认跳转到第一个菜单
  const topMenus = authStore.getAuthLeftMenus
  goToFirstMenu(topMenus)
}

/**
 * 默认跳转到左侧第一个菜单
 */
const goToFirstMenu = (menus: RouteRecordRaw[]) => {
  if (menus.length === 0) return
  const [first] = menus
  if (first.children && first.children.length > 0) {
    goToFirstMenu(first.children as RouteRecordRaw[])
  } else if (first.name) {
    router.push({
      name: first.name
    })
  }
}

/**
 * 初始化顶部菜单
 */
onMounted(() => {
  topMenus.value = authStore.getAuthRoutes.filter(item => !item.meta || !item.meta.hidden)
})
</script>

<style lang="scss" scoped>
:deep(.el-menu) {
  // border: none;
  width: 100%;
  height: 100%;

  // overflow-x: hidden;
}
</style>
